import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter_elm/json/business_item.dart';
import 'package:flutter_elm/json/business_item.dart';
import 'package:flutter_elm/json/business_item.dart';
import 'package:flutter_elm/json/response_item.dart';
import 'package:flutter_elm/json/user_item.dart';

//code 2开头都是请求成功的，只不过业务上可能不成功
//code 4开头都是请求不成功的。（一般都是 客户端-前端代码问题）
class BusinessApi {
  late Dio _dio;
  String baseUrl = "http://192.168.1.12:8080/BusinessController";
  String contents = "";

  BusinessApi() {
    _dio = Dio();
    // 设置contentType
    // _dio.options.headers['Content-Type'] = 'application/x-www-form-unlencoded';
  }

  var response = null;
  //注意，在界面调用接口前， 都先检测一下apikey的值。
  Future<ResponseItem<List<BusinessItem>?>> getBusinessByType(int type) async {
    var url =  baseUrl+"/listAllBusinessByType/${type}";

    try {
      response = await _dio.get(url);
//如果没有该type类型，或者该类型没有商家，就会返回[]
//       print(response.data);
      if(response.data.length==0){
        return ResponseItem(code: 201, data: null, message: "没有该type类型，或者该类型没有商家");
      }else{
        List rd = response.data;
        List<BusinessItem> businessItemList = rd.map((e) => BusinessItem.fromJson(e)).toList();
        return ResponseItem<List<BusinessItem>>(code: 200, data: businessItemList, message: "查找成功");
      }
    } catch (e) {
        if(response.data.length==0){
          print('******getBusinessByType-Error: $e');
          return ResponseItem(code: 400, data: null, message: "客户端代码有问题，$e");
        }else{
          print('******getBusinessByType-Error: $e');
          List rd = response.data;
          List<BusinessItem> businessItemList = rd.map((e) => BusinessItem.fromJson(e)).toList();
          return ResponseItem<List<BusinessItem>>(code: 202, data: businessItemList, message: "查找成功，但是系统发现错误：$e");
        }
    }
  }

}

void main()async{
  BusinessApi businessApi = BusinessApi();
  // var res = await userApi.userRegister("11111178912", "12345678912", "小李", 1);
  var res = await businessApi.getBusinessByType(4);
  print("${res.code}:${res.message}");
  // print("${res.code}:${res.message}\n查找结果：${res.data}");
}


// //出现问题： 在获取到数据的情况下，会报错：RangeError (index): Invalid value: Valid value range is empty: 0
// //但这个错貌似是因为环境配置原因，时而成功，时而失败，狗屎啊。无法从代码上解决，因此将response设置为本地变量。做一个if-else判断来进行返回，
// //确保可解决的问题能够被返回，获取到的数据被返回
// if(response.data.length==0){
// print('******getBusinessByType-Error: $e');
// return ResponseItem(code: 400, data: null, message: "客户端代码有问题");
// }else{
// List rd = response.data;
// print("${rd[0]["ordersList"][0].runtimeType}");
// List<BusinessItem> businessItemList = rd.map((e) => BusinessItem.fromJson(e)).toList();
// return ResponseItem<List<BusinessItem>>(code: 200, data: businessItemList, message: "查找成功");
// }